// 工具函数集

// 格式化时间
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

// 格式化数字
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

// 格式化会员到期时间
const formatVipExpireDate = dateStr => {
  if (!dateStr) return '未开通';
  
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  
  return `${year}年${month}月${day}日`;
}

// 检查是否为VIP
const checkIsVip = expireDate => {
  if (!expireDate) return false;
  
  const now = new Date();
  const expireDateTime = new Date(expireDate);
  
  return now < expireDateTime;
}

// 显示加载提示
const showLoading = (title = '加载中') => {
  tt.showLoading({
    title,
    mask: true
  });
}

// 隐藏加载提示
const hideLoading = () => {
  tt.hideLoading();
}

// 显示成功提示
const showSuccess = (title, duration = 1500) => {
  tt.showToast({
    title,
    icon: 'success',
    duration
  });
}

// 显示失败提示
const showError = (title, duration = 1500) => {
  tt.showToast({
    title,
    icon: 'error',
    duration
  });
}

// 显示普通提示
const showToast = (title, duration = 1500) => {
  tt.showToast({
    title,
    icon: 'none',
    duration
  });
}

// 显示确认对话框
const showModal = (title, content, showCancel = true) => {
  return new Promise((resolve, reject) => {
    tt.showModal({
      title,
      content,
      showCancel,
      success: res => {
        if (res.confirm) {
          resolve(true);
        } else if (res.cancel) {
          resolve(false);
        }
      },
      fail: reject
    });
  });
}

// 检查积分是否足够
const checkCreditsEnough = (app, needCredits = 1) => {
  const credits = app.globalData.credits || 0;
  const freeCredits = app.globalData.freeCredits || 0;
  
  return credits >= needCredits || freeCredits > 0;
}

// 消耗积分
const consumeCredits = (app, needCredits = 1) => {
  // 优先使用免费次数
  if (app.globalData.freeCredits > 0) {
    console.log(`使用免费次数: 当前${app.globalData.freeCredits}次，消耗1次`);
    app.useOneFreeCredit();
    return true;
  }
  
  // 如果积分足够，返回true
  if (app.globalData.credits >= needCredits) {
    console.log(`使用积分: 当前${app.globalData.credits}积分，消耗${needCredits}积分`);
    // 积分消耗由服务端处理
    return true;
  }
  
  // 积分不足
  console.log(`积分和免费次数都不足: 当前积分${app.globalData.credits}，免费次数${app.globalData.freeCredits}`);
  return false;
}

module.exports = {
  formatTime,
  formatNumber,
  formatVipExpireDate,
  checkIsVip,
  showLoading,
  hideLoading,
  showSuccess,
  showError,
  showToast,
  showModal,
  checkCreditsEnough,
  consumeCredits
} 